package com.itqf.realm;

import com.itqf.entity.SysUser;
import com.itqf.service.SysUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;

/**
 * @Description:
 * @Company: 千锋互联
 * @Author: 李丽婷
 * @Date: 2020/10/19
 * @Time: 下午3:01
 */
//<bean id="myUserRealm" class="com.itqf.realm.MyUserRealm"></bean>
public class MyUserRealm extends AuthorizingRealm {

    //注入service
    @Resource //  从spring容器中注入
    private SysUserService sysUserService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        String   username = (String)token.getPrincipal();
        String  password = new String((char[])token.getCredentials());

        //跟数据库比较
        SysUser sysUser = sysUserService.login(username);
        if (sysUser==null){
            throw  new UnknownAccountException("用户名错误");
        }

        if (!sysUser.getPassword().equals(password)){
            throw  new IncorrectCredentialsException("密码错误");
        }

        if (sysUser.getStatus()!=1){
            throw  new LockedAccountException("账号被禁用，请联系管理员");
        }

        SimpleAuthenticationInfo info = new
                SimpleAuthenticationInfo(sysUser,password,this.getName());

        return info;


    }
}
